//
//  WSManager.m
//  mUBB
//
//  Created by Cosmin Stirbu on 1/13/13.
//  Copyright (c) 2013 Cosmin Stirbu. All rights reserved.
//

#import "WSManager.h"
#import "Connection.h"
#import "ConfigurationManager.h"

@interface WSManager(Private)

@end


@implementation WSManager

// Singleton 
+ (WSManager *)instance
{
    static WSManager *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[WSManager alloc] init];
        // Do any other initialisation stuff here
    });
    return instance;
}

- (id)init {
    self = [super init];    
    ticketId = 0;
    
    return self;
}

- (void)getRequestWithUrl:(NSString *)url andHeaders:(NSDictionary *)headers {
    [self createNewConnectionWithUrl:url httpHeaders:headers httpMethod:@"GET" httpBody:nil];
}

- (void)postRequestWithUrl:(NSString *)url body:(NSString *)body andHeaders:(NSDictionary *)headers {
    [self createNewConnectionWithUrl:url httpHeaders:headers httpMethod:@"POST" httpBody:body];
}

- (void)putRequestWithUrl:(NSString *)url body:(NSString *)body andHeaders:(NSDictionary *)headers {
    [self createNewConnectionWithUrl:url httpHeaders:headers httpMethod:@"PUT" httpBody:body];
}

- (void)deleteRequestWithUrl:(NSString *)url body:(NSString *)body andHeaders:(NSDictionary *)headers {
    [self createNewConnectionWithUrl:url httpHeaders:headers httpMethod:@"DELETE" httpBody:body];
}

- (void)createNewConnectionWithUrl:(NSString *)url httpHeaders:(NSDictionary *)headers httpMethod:(NSString *)method httpBody:(NSString*) body{
    // Create new HTTP request
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:WS_TIMEOUT_INTERVAL];
    // Set HTTP Method
    [request setHTTPMethod:method];
    // Set HTTP Body
    if (body != nil) {
        [request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
    }
    // Set headers
    for (NSString *key in [headers allKeys]) {
        [request addValue:[headers objectForKey:key] forHTTPHeaderField:key];
    }
    // Set authorization
    [request setValue:[[ConfigurationManager instance] applicationConfigValueForKey:ACCESS_TOKEN] forHTTPHeaderField:@"Authorization"];
    
    // Set Language
    NSString *language = [[NSLocale preferredLanguages] objectAtIndex:0];
    [request setValue:language forHTTPHeaderField:@"Accept-Language"];
    
    // Create connection
    Connection *connection = [[Connection alloc] initWithRequest:request delegate:connectionDelegate];
    // Execute request
    [connection executeRequest];
}

@end
